package demo2;

import com.sun.org.apache.xerces.internal.impl.xs.opti.DefaultNode;
import demo1.SetFont;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.Set;

public class TreeWin extends JFrame implements TreeSelectionListener {
    JTree tree ;
    JTextArea showText ;
    public TreeWin(){
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("商品");
        DefaultMutableTreeNode nodeTv = new DefaultMutableTreeNode("电视机类");
        DefaultMutableTreeNode nodePhone = new DefaultMutableTreeNode("手机类");
        DefaultMutableTreeNode tv1 =
                new DefaultMutableTreeNode(new Goods("长虹电视",666));
        DefaultMutableTreeNode tv2 =
                new DefaultMutableTreeNode(new Goods("海尔电视",999));
        DefaultMutableTreeNode tv3 =
                new DefaultMutableTreeNode(new Goods("小米电视",500));
        DefaultMutableTreeNode phone1 =
                new DefaultMutableTreeNode(new Goods("苹果手机",9999));
        DefaultMutableTreeNode phone2 =
                new DefaultMutableTreeNode(new Goods("华为手机",8888));
         root.add(nodeTv);
         root.add(nodePhone);
         nodeTv.add(tv1);
         nodeTv.add(tv2);
         nodeTv.add(tv3);
         nodePhone.add(phone1);
         nodePhone.add(phone2);
         this.tree = new JTree(root);
          tree.addTreeSelectionListener(this);
          showText = new JTextArea();
          setLayout(new GridLayout(1,2));
          add(new JScrollPane(tree));
          add(new JScrollPane(showText));
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setVisible(true);
          setBounds(80,80,600,500);
         Font font = new Font("宋体",Font.PLAIN,22);
        SetFont.setFont(font , showText , tree);
        validate();

    }
    @Override
    public void valueChanged(TreeSelectionEvent e) {
  DefaultMutableTreeNode node =
          (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if(node == null){
        return;
    }
    if(node.isLeaf()){
        Goods goods = (Goods) node.getUserObject();
        showText.append(goods.name + "  "+goods.price + " 元\n" );
    }else{
        showText.setText(null);
    }
    }
}
